<?php
/**
 * @title 54. 螺旋矩阵 - 迭代
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[][] $matrix
     * @return Integer[]
     */
    function spiralOrder($matrix) {
        /**
         * @since 2020-09-14 结果集
         */
        $result = [];

        /**
         * @since 2020-09-14 高宽
         */
        $h = count($matrix);
        $w = count($matrix[0]);

        /**
         * @since 2020-09-14 4个方便逼近
         */
        $h1 = 0;
        $h2 = $h-1;
        $w1 = 0;
        $w2 = $w-1;
        while($h1<=$h2 AND $w1<=$w2){
            /**
             * @since 2020-09-14 [左上, 右上]
             */
            for($i=$w1; $i<=$w2; $i++){
                $result[] = $matrix[$h1][$i];
            }

            /**
             * @since 2020-09-14 (右上, 右下]
             */
            for($i=$h1+1; $i<=$h2; $i++){
                $result[] = $matrix[$i][$w2];
            }

            /**
             * @since 2020-09-14 (右下, 左下]
             */
            if($h2>$h1){
                for($i=$w2-1; $i>=$w1; $i--){
                    $result[] = $matrix[$h2][$i];
                }
            } else {}


            /**
             * @since 2020-09-14 (左下, 左上)
             */
            if($w2>$w1){
                for($i=$h2-1; $i>=$h1+1; $i--){
                    $result[] = $matrix[$i][$w1];
                }
            } else {}

            $h1++;
            $w1++;
            $h2--;
            $w2--;
        }

        /**
         * @return
         */
        return $result;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.22_8.php
 */
$datas = [
    [
        [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ]
    ],
    [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9,10,11,12]
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->spiralOrder($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
